from fastapi import APIRouter, Depends, Request
from starlette.responses import HTMLResponse

from applications.common.render_template import templates
from applications.common.user_manager import permission_depends
from applications.utils.http import fail_api, success_api, table_api, PageResponse
from applications.models import Power
from applications.schemas.admin_power import (
    PowerEnableDisableSchema,
    PowerOutSchema,
    PowerSaveSchema,
    PowerUpdateSchema,
    PowerTree,
    MenuOut,
)

route = APIRouter(prefix="/power", tags=["系统管理-菜单管理"])


@route.get(
    "/",
    name="system.power.main",
    dependencies=[Depends(permission_depends("system:power:main"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def index(request: Request):
    return templates.TemplateResponse("system/power/main.html", {"request": request})


@route.post(
    "/data",
    dependencies=[Depends(permission_depends("system:power:main"))],
    summary="获取权限列表",
    response_model=PageResponse[PowerTree],
)
async def get_power_list():
    powers = await Power.all()
    data = [PowerOutSchema.model_validate(power).model_dump() for power in powers]

    # 创建一个字典，用于存储每个节点的子节点
    tree = {}
    for item in data:
        item["children"] = []
        tree[item["id"]] = item

    # 构建树形结构
    root_nodes = []
    for item in data:
        parent_id = item["parent_id"] if item["parent_id"] != 0 else None
        if parent_id is None:
            root_nodes.append(item)
        else:
            if parent_id in tree:
                tree[parent_id]["children"].append(item)

    return table_api(msg="请求成功", data=root_nodes)


@route.get(
    "/add",
    dependencies=[Depends(permission_depends("system:power:add"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def add(request: Request):
    return templates.TemplateResponse("system/power/add.html", {"request": request})


@route.get("/selectParent", dependencies=[Depends(permission_depends("system:power:main"))], summary="选择上级权限")
async def select_parent():
    powers = await Power.all()
    res = [MenuOut.model_validate(power).model_dump() for power in powers]

    # 调整字段名以匹配前端期望的格式
    formatted_res = []
    for item in res:
        formatted_res.append({"powerId": item["id"], "powerName": item["title"], "parentId": item["parent_id"]})

    formatted_res.append({"powerId": 0, "powerName": "顶级权限", "parentId": -1})
    res = {"status": {"code": 200, "message": "默认"}, "data": formatted_res}
    return res


# 增加权限
@route.post("/save", dependencies=[Depends(permission_depends("system:power:add"))], summary="保存权限")
async def save(data: PowerSaveSchema):
    power_data = data.model_dump()
    power = Power(**power_data)
    await power.save()
    return success_api(msg="权限添加成功")


# 权限编辑
@route.get(
    "/edit/{pk}",
    dependencies=[Depends(permission_depends("system:power:edit"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def edit(request: Request, pk: int):
    power = await Power.get_or_none(id=pk)
    if not power:
        return fail_api(msg="权限不存在")

    icon = str(power.icon).split()
    if len(icon) == 2:
        icon = icon[1]
    else:
        icon = None

    return templates.TemplateResponse("system/power/edit.html", {"request": request, "power": power, "icon": icon})


# 权限更新
@route.put("/update", dependencies=[Depends(permission_depends("system:power:edit"))], summary="更新权限")
async def update(data: PowerUpdateSchema):
    # 直接使用model_dump(by_alias=True)来获取使用别名的字典
    power_data = data.model_dump(exclude={"id"})

    power = await Power.get_or_none(id=data.powerId)
    if not power:
        return fail_api(msg="权限不存在")

    for key, value in power_data.items():
        if hasattr(power, key):
            setattr(power, key, value)

    await power.save()
    return success_api(msg="更新权限成功")


# 启用权限
@route.put("/enable", dependencies=[Depends(permission_depends("system:power:edit"))], summary="启用权限")
async def enable(data: PowerEnableDisableSchema):
    power = await Power.get_or_none(id=data.powerId)
    if not power:
        return fail_api(msg="权限不存在")

    power.enable = 1
    await power.save()
    return success_api(msg="启用成功")


# 禁用权限
@route.put("/disable", dependencies=[Depends(permission_depends("system:power:edit"))], summary="禁用权限")
async def dis_enable(data: PowerEnableDisableSchema):
    power = await Power.get_or_none(id=data.powerId)
    if not power:
        return fail_api(msg="权限不存在")

    power.enable = 0
    await power.save()
    return success_api(msg="禁用成功")


# 权限删除
@route.delete("/remove/{pk}", dependencies=[Depends(permission_depends("system:power:remove"))], summary="删除权限")
async def remove(pk: int):
    power = await Power.get_or_none(id=pk)
    if not power:
        return fail_api(msg="权限不存在")

    await power.delete()
    return success_api(msg="删除成功")


# 批量删除
@route.delete("/batchRemove", dependencies=[Depends(permission_depends("system:power:remove"))], summary="批量删除权限")
async def batch_remove(ids: list[int]):
    if not ids:
        return fail_api(msg="未提供删除 ID")

    await Power.filter(id__in=ids).delete()

    return success_api(msg="批量删除成功")
